package com.sunny.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sunny.common.Const;
import com.sunny.common.TokenCache;
import com.sunny.dao.UserMapper;
import com.sunny.pojo.House;
import com.sunny.pojo.User;
import com.sunny.service.IUserService;
import com.sunny.utils.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.UUID;

/**
 * @ClassName:
 * @Description:
 * @author: yubao.jin
 * @date: 2018/5/13
 * @version:V1.0
 */
@Service("iUserService")
public class UserServiceImpl implements IUserService{
    @Autowired
    private UserMapper userMapper;

    @Override
    public ServerResponse<User> login(String username, String password) {
        int resultCount = userMapper.checkname(username);
        if (resultCount == 0) {
            return ServerResponse.createByErrorMessage("用户名不存在");
        }

        // 密码登陆MD5
        String md5Password = MD5Util.MD5EncodeUtf8(password);
        User user = userMapper.selectLogin(username, md5Password);
        if (user == null) {
            return ServerResponse.createByErrorMessage("密码错误");
        }

        // 密码设置为空
        user.setPassword(StringUtils.EMPTY);
        return ServerResponse.createBySuccess("登陆成功", user);
    }

    @Override
    public ServerResponse<String> register(User user) {
        ServerResponse validResponse = this.checkValid(user.getName(), Const.USERNAME);
        if(!validResponse.isSuccess()) {
            return validResponse;
        }

        // MD5加密
        user.setPassword(MD5Util.MD5EncodeUtf8(user.getPassword()));
        int resultCount = userMapper.insert(user);
        if(resultCount == 0) {
            return ServerResponse.createByErrorMessage("注册失败");
        }

        return ServerResponse.createBySuccessMessage("注册成功");
    }

    @Override
    public ServerResponse<String> checkValid(String str, String type) {
        if(StringUtils.isNoneBlank(type)) {
            // 开始校验
            if(Const.USERNAME.equals(type)) {
                int resultCount = userMapper.checkname(str);
                if(resultCount > 0) {
                    return ServerResponse.createByErrorMessage("用户名已存在");
                }
            }

            /*if(Const.EMAIL.equals(type)) {
                int resultCount = userMapper.checkEmail(str);
                if(resultCount > 0) {
                    return ServerResponse.createByErrorMessage("邮箱地址已存在");
                }
            }*/
        } else {
            return ServerResponse.createByErrorMessage("参数错误");
        }

        return ServerResponse.createBySuccessMessage("校验成功");
    }

    @Override
    public ServerResponse selectQuestion(String username) {
        ServerResponse validResponse = this.checkValid(username, Const.USERNAME);
        if(validResponse.isSuccess()) {
            // 用户不存在
            return ServerResponse.createByErrorMessage("用户不存在");
        }

        String question = userMapper.selectQuestionByname(username);
        if(StringUtils.isNoneBlank(question)) {
            return ServerResponse.createBySuccess(question);
        }
        return ServerResponse.createByErrorMessage("找回密码的问题是空的");
    }

    @Override
    public ServerResponse<String> checkAnswer(String username, String question, String answer) {
        int resultCount = userMapper.checkAnswer(username, question, answer);
        if(resultCount > 0) {
            // 说明问题和问题答案是这个用户的，并且是正确的
            String forgetToken = UUID.randomUUID().toString(); // 宇宙无敌不可重复的字符串
            TokenCache.setKey(TokenCache.TOKEN_PREFIX + username, forgetToken);
            return ServerResponse.createBySuccess(forgetToken);
        }
        return ServerResponse.createByErrorMessage("问题的答案错误");
    }

    @Override
    public ServerResponse<String> forgetResetPassword(String username, String passwordNew, String forgetToken) {
        if(StringUtils.isBlank(forgetToken)) {
            return ServerResponse.createByErrorMessage("參數錯誤，token需要傳遞");
        }

        ServerResponse validResponse = this.checkValid(username, Const.USERNAME);
        if(validResponse.isSuccess()) {
            // 用戶不存在
            return ServerResponse.createByErrorMessage("用戶不存在");
        }

        String token = TokenCache.getKey(TokenCache.TOKEN_PREFIX + username);
        if(StringUtils.isBlank(token)) {
            return ServerResponse.createByErrorMessage("token無效或已過期");
        }

        // 使用StringUtils是不會出現空指針異常的
        if(StringUtils.equals(forgetToken, token)) {
            String md5Password = MD5Util.MD5EncodeUtf8(passwordNew);
            int rowCount = userMapper.updatePasswordByname(username, md5Password);
            if(rowCount > 0) {
                return ServerResponse.createBySuccessMessage("修改密碼成功");
            }
        } else {
            return ServerResponse.createByErrorMessage("token錯誤，請重新獲取token");
        }

        return ServerResponse.createByErrorMessage("修改密碼失敗");
    }

    @Override
    public ServerResponse<String> resetPassword(String passwordOld, String passwordNew, User user) {
        // 防止橫向越權，需要校驗用戶舊密碼，一定要制定這個用戶，
        // 因爲我們會查詢一個count(1), 如果不指定id,那麽結果就是true，count(1) > 0
        int resultCount = userMapper.checkPassword(MD5Util.MD5EncodeUtf8(passwordOld), user.getId());
        if(resultCount == 0) {
            return ServerResponse.createByErrorMessage("舊密碼錯誤");
        }

        user.setPassword(MD5Util.MD5EncodeUtf8(passwordNew));
        int updateCount = userMapper.updateByPrimaryKeySelective(user);
        if(updateCount > 0) {
            return ServerResponse.createBySuccessMessage("更新密碼成功");
        } else {
            return ServerResponse.createByErrorMessage("密碼更新失敗");
        }
    }

    @Override
    public ServerResponse<User> updateInformation(User user) {
        // username不能被更新的
        // email也要進行一個校驗，校驗新的email是不是已經存在，并且存在的email如果相同的話，不能是當前的這個用戶的
        int resultCount = userMapper.checkEmailByUserId(user.getEmail(), user.getId());
        if(resultCount > 0) {
            return ServerResponse.createByErrorMessage("email已經被其他用戶占用，請更換email再嘗試更新");
        }

        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setEmail(user.getEmail());
        updateUser.setPhone(user.getPhone());

        int updateCount = userMapper.updateByPrimaryKeySelective(updateUser);
        if(updateCount > 0) {
            return ServerResponse.createBySuccess("更新個人信息成功", updateUser);
        }

        return ServerResponse.createByErrorMessage("更新個人信息失敗");
    }

    @Override
    public ServerResponse<User> getInformation(Integer userId) {
        User user = userMapper.selectByPrimaryKey(userId);
        if(user == null) {
            return ServerResponse.createByErrorMessage("找不到当前用户");
        }
        user.setPassword(StringUtils.EMPTY);
        return ServerResponse.createBySuccess(user);
    }

    // backend
    @Override
    public ServerResponse checkAdminRole(User user) {
        // 注意将Integer类型转化为int类型再进行比较
        if(user != null && user.getRoleNo().intValue() == Const.Role.ROLE_ADMIN) {
            return ServerResponse.createBySuccess();
        }
        return ServerResponse.createByError();
    }

    @Override
    public PageInformation<User> list(PageUtil page, User user) {
        // 利用pageHelper进行分页查询
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        List<User> list = userMapper.selectUserByuser(user);
        PageInfo<User> pageInfo = new PageInfo(list);
        list = pageInfo.getList();
        // 改变日期格式
        for(User u : list) {
            u.setCreTime(DateTimeUtil.dateToStr(u.getCreateTime()));
            u.setUpdaTime(DateTimeUtil.dateToStr(u.getUpdateTime()));
        }
        // 组装PageInformation返回前端数据
        PageInformation<User> pageInformation =  PageInformation.getInstance();
        pageInformation.setRows(pageInfo.getList());
        pageInformation.setTotal(pageInfo.getTotal());
        return pageInformation;
    }

    @Override
    public ServerResponse del(String[] id) {
        if(id != null  && id.length==0) {
            return ServerResponse.createByErrorMessage("您未选择，请重新选择");
        }

        // 数组转化为list
        List<String> idList = Arrays.asList(id);
        int resultCount = userMapper.deleteByIds(idList);
        // 检验
        if(resultCount == 0) {
            return ServerResponse.createByErrorMessage("删除失败");
        }

        return ServerResponse.createBySuccessMessage("删除成功");
    }
}
